<script setup lang="ts">
import {StoreForm} from "@/api/store/types";

/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "FileAudit",
  inheritAttrs: false,
});
import {
  getFileAuditPage,
  antiAudit
} from "@/api/fileAudit";
import {useRouter} from "vue-router";

import { FileAuditQuery } from "@/api/fileAudit/types";
import {RoleForm} from "@/api/role/types";
import {CompanyForm} from "@/api/company/types";
import {listAll} from "@/api/store";
import {getAllRole} from "@/api/role";
import {getCompanyList} from "@/api/company";
import moment from "moment/moment";
import lodash from "lodash-es";

const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const showMore = ref(false);
const total = ref(0);
const monthList = ref<[]>([])
const storeList = ref<StoreForm[]>();
const roleList = ref<RoleForm[]>();
const companyList = ref<CompanyForm[]>();
const tableHeight = ref(150)

const queryParams = reactive<FileAuditQuery>({
  pageNum: 1,
  pageSize: 20,
});
const auditList = ref<[]>();
const router = useRouter();



/**
 * 查询
 */
function handleQuery() {
  queryParams.ownerLoss = queryParams.ownerLossValue ? 1 : null;
  loading.value = true;
	if (lodash.size(monthList.value) > 0){
		lodash.set(queryParams, 'startMonth', monthList.value[0])
		lodash.set(queryParams, 'endMonth', monthList.value[1])
	}
  getFileAuditPage(queryParams)
    .then(({ data }) => {
	  	auditList.value = data.list;
      total.value = data.total;
			getHeight()
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 跳转到详情页
 * @param id
 * @param goType 跳转类型（0：待审核，1：已办未归档、归档，2：归档核销表）
 */
function goDetail(id: number, linkNo: string, businessDate: any, goType: number) {
	let splitDatas = businessDate.split('-')
	let billMonth = splitDatas[0] + splitDatas[1]
  router.push({
    name: 'AuditDetail',
    state: {
      id: id,
      goType: goType,
			linkNo: linkNo,
      billMonth: billMonth
    }
  })
}

/**
 * 获取所有店铺
 */
function getAllStore() {
	listAll().then((response) => {
		storeList.value = []
		const group_store = lodash.groupBy(response.data, 'storeKeyName');
		for (let key in group_store) {
			storeList.value.push({'label': key, 'options': group_store[key]})
		}
	})
}

/**
 * 获取角色下拉列表
 */
function getRoleOptions() {
  getAllRole().then((response) => {
    roleList.value = response.data;
  });
}

/**
 * 获取入账主体列表
 *
 */
function getAllCompanyList() {
  getCompanyList().then((response) => {
    companyList.value = response.data;
  });
}

/**
 * 反审核
 */
function antiAuditHandle(id: number){
  antiAudit(id, monthValue.value).then(() => {
    ElMessage.success('操作成功');
  });
}

function getHeight() {
	if (showMore.value) {
		if (auditList.value && auditList.value.length > 0) {
			tableHeight.value = 534
		} else {
			tableHeight.value = 150
		}
	}else{
		if (auditList.value && auditList.value.length > 0) {
			tableHeight.value = 640
		}else{
			tableHeight.value = 150
		}
	}
}

function showMoreHandle() {
	showMore.value = !showMore.value
	getHeight()
}

onMounted(() => {
	let now = new Date()
	let month = now.getMonth()
	let nowMonth;
	if (month < 9){
		nowMonth = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
	}	else {
		nowMonth = now.getFullYear() + '' + (now.getMonth() + 1) + ''
	}
	monthList.value = [nowMonth, nowMonth]
  handleQuery(); // 初始化标准账单配置列表数据
  getAllStore()
  getRoleOptions()
  getAllCompanyList()
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col>
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="业务日期">
							<el-date-picker
									style="width: 200px"
									v-model="monthList"
									type="monthrange"
									range-separator="至"
									start-placeholder="开始月份"
									end-placeholder="结束月份"
									value-format="YYYYMM"
									:clearable="false"
							/>
            </el-form-item>
						<el-form-item label="内部系统店铺名称" prop="shopCode">
							<el-select class="yz-el-select" v-model="queryParams.shopCode" filterable clearable placeholder="请选择店铺">
								<el-option-group
									v-for="group in storeList"
									:key="group.label"
									:label="group.label"
								>
									<el-option
										v-for="item in group.options"
										:key="item.id"
										:label="item.innerSystemStoreName"
										:value="item.innerSystemStoreCode"
									/>
								</el-option-group>
							</el-select>
						</el-form-item>
						<el-form-item label="原始账单ID" prop="linkNo">
							<el-input
									v-model="queryParams.linkNo"
									placeholder="原始主订单号"
									clearable
									style="width: 200px"
							/>
						</el-form-item>
            <el-form-item label="单据编号" prop="keywords">
              <el-input
                      v-model="queryParams.keywords"
                      placeholder="单据编号"
                      clearable
                      style="width: 200px"
              />
            </el-form-item>
            <el-form-item v-if="showMore" label="入账主体" prop="receiveCompany">
              <el-select
                      v-model="queryParams.receiveCompany"
                      placeholder="全部"
                      clearable
											class="yz-el-select"
              >
                <el-option
                        v-for="item in companyList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="showMore" label="电商平台店铺名称" prop="thirdSourceCode">
							<el-select class="yz-el-select" v-model="queryParams.thirdSourceCode" filterable clearable placeholder="请选择店铺">
								<el-option-group
									v-for="group in storeList"
									:key="group.label"
									:label="group.label"
								>
									<el-option
										v-for="item in group.options"
										:key="item.id"
										:label="item.innerSystemStoreName"
										:value="item.commercePlatformStoreCode"
									/>
								</el-option-group>
							</el-select>
            </el-form-item>
            <el-form-item v-if="showMore" label="财务系统店铺名称" prop="billSysStore">
							<el-select class="yz-el-select" v-model="queryParams.storeId" filterable clearable placeholder="请选择店铺">
								<el-option-group
									v-for="group in storeList"
									:key="group.label"
									:label="group.label"
								>
									<el-option
										v-for="item in group.options"
										:key="item.id"
										:label="item.innerSystemStoreName"
										:value="item.financeSystemStoreCode"
									/>
								</el-option-group>
							</el-select>
            </el-form-item>
            <el-form-item v-if="showMore" label="核销结果分类" prop="mainTypeName">
              <dictionary v-model="queryParams.mainTypeName" type-code="jgfl"/>
            </el-form-item>
            <el-form-item v-if="showMore" label="损失原因" prop="lossReason">
              <dictionary v-model="queryParams.lossReason" type-code="loss"/>
            </el-form-item>
            <el-form-item v-if="showMore" label="责任方" prop="push">
              <el-select
                      v-model="queryParams.push"
                      placeholder="全部"
                      clearable
											class="yz-el-select"
              >
                <el-option
                        v-for="item in roleList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="showMore" label="PO单号" prop="poNo">
              <el-input
                      v-model="queryParams.poNo"
                      placeholder="PO单号"
                      clearable
                      style="width: 200px"
              />
            </el-form-item>
            <el-form-item v-if="showMore" label="自有平台主订单号" prop="onwerPreformNo">
              <el-input
                      v-model="queryParams.onwerPreformNo"
                      placeholder="自有平台主订单号"
                      clearable
                      style="width: 200px"
              />
            </el-form-item>
            <el-form-item v-if="showMore" label="是否自认损失" prop="ownerLossValue">
              <el-checkbox style="margin-top: -3px;" v-model="queryParams.ownerLossValue" label="是" size="large"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="resetQuery"
                ><i-ep-search />搜索</el-button
              >
						<el-button type="primary" @click="showMoreHandle()" >{{showMore ? '隐藏更多' : '更多查询'}}</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">

          <el-table
            size="small"
            :height="tableHeight"
            :header-row-style="{color: 'dimgray'}"
            v-loading="loading"
            :data="auditList"
						border
          >
						<el-table-column
								fixed="left"
								label="原始单据ID"
								align="center" show-overflow-tooltip
								width="180"
						>
							<template #default="scope">
								<img v-if="scope.row.manager === 1" src="@/assets/hot.gif"/><a style="color:cornflowerblue"
																							 href="javascript:;"
																							 @click="goDetail(scope.row.id, scope.row.linkNo, scope.row.businessDate, 2)">{{scope.row.linkNo}}</a>
							</template>
						</el-table-column>
						<el-table-column
								label="内部系统店铺名称"
								align="center" show-overflow-tooltip
								prop="shopName"
								width="80"
						/>
						<el-table-column
								label="财务系统店铺名称"
								align="center" show-overflow-tooltip
								prop="billSysStoreName"
								width="80"
						></el-table-column>
						<el-table-column
								label="电商平台店铺名称"
								align="center" show-overflow-tooltip
								prop="thirdSourceName"
								width="80"
						></el-table-column>
						<el-table-column
								label="业务日期"
								align="center" show-overflow-tooltip
								prop="businessDate"
								width="140"
						/>
						<el-table-column
								label="核销结果分类"
								align="center" show-overflow-tooltip
								prop="mainTypeName"
								width="80"
						></el-table-column>
						<el-table-column
								label="规则名称"
								align="center" show-overflow-tooltip
								prop="ruleName"
								width="80"
						/>
						<el-table-column
								label="核销状态"
								align="center" show-overflow-tooltip
								prop="auditStatus"
								width="80"
						/>
						<el-table-column
								label="应收账款余额"
								align="center" show-overflow-tooltip
								prop="receiveBillAmount"
								width="80"
						/>
						<el-table-column
								label="发货金额"
								align="center" show-overflow-tooltip
								prop="sendAmount"
								width="80"
						/>
						<el-table-column
								label="退货金额"
								align="center" show-overflow-tooltip
								width="80"
						>
							<template #default="scope">{{scope.row.returnAmount === 0 ? '' : scope.row.returnAmount}}</template>
						</el-table-column>
						<el-table-column
								label="收款金额"
								align="center" show-overflow-tooltip
								prop="receiveAmount"
								width="80"
						/>
						<el-table-column
								label="退款金额"
								align="center" show-overflow-tooltip
								width="80"
						>
							<template #default="scope">{{scope.row.refundAmount === 0 ? '' : scope.row.refundAmount}}</template>
						</el-table-column>
						<el-table-column
								label="保证金退款金额"
								align="center" show-overflow-tooltip
								width="80"
						>
							<template #default="scope">{{scope.row.depositAmount === 0 ? '' : scope.row.depositAmount}}</template>
						</el-table-column>
						<el-table-column
								label="发货数量"
								align="center" show-overflow-tooltip
								prop="qty"
								width="80"
						></el-table-column>
						<el-table-column
								label="退货数量"
								align="center" show-overflow-tooltip
								width="80"
						>
							<template #default="scope">{{scope.row.returnQty === 0 ? '' : scope.row.returnQty}}</template>
						</el-table-column>
						<el-table-column
								label="收款日期"
								align="center" show-overflow-tooltip
								prop="receiveDate"
								width="140"
						></el-table-column>
						<el-table-column
								label="退款日期"
								align="center" show-overflow-tooltip
								prop="refundDate"
								width="140"
						></el-table-column>
						<el-table-column
								label="自系统调账日期"
								align="center" show-overflow-tooltip
								prop="systemReconciliationDate"
								width="140"
						></el-table-column>
						<el-table-column
								label="自系统调账数量"
								align="center" show-overflow-tooltip
								prop="systemReconciliationQty"
								width="80"
						></el-table-column>
						<el-table-column
								label="自系统调账金额"
								align="center" show-overflow-tooltip
								prop="systemReconciliationAmount"
								width="80"
						></el-table-column>
						<el-table-column
								label="财务调账日期"
								align="center" show-overflow-tooltip
								prop="reconciliationDate"
								width="140"
						></el-table-column>
						<el-table-column
								label="财务调账数量"
								align="center" show-overflow-tooltip
								prop="reconciliationQty"
								width="80"
						></el-table-column>
						<el-table-column
								label="财务调账金额"
								align="center" show-overflow-tooltip
								prop="reconciliationAmount"
								width="80"
						></el-table-column>
						<el-table-column
								label="单据编号"
								align="center" show-overflow-tooltip
								prop="orderNo"
								width="80"
						></el-table-column>
						<el-table-column
								label="对账系统平台名称"
								width="80"
								align="center" show-overflow-tooltip
								prop="secordSourceName"
						/>
						<el-table-column
								label="内部系统电商平台名称"
								align="center" show-overflow-tooltip
								prop="innerShopName"
								width="80"
						></el-table-column>
						<el-table-column
								label="自有平台主订单号"
								align="center" show-overflow-tooltip
								prop="onwerPreformNo"
								width="80"
						></el-table-column>
						<el-table-column
								label="PO单号"
								align="center" show-overflow-tooltip
								prop="poNo"
								width="80"
						></el-table-column>
						<el-table-column
								label="入账主体"
								align="center" show-overflow-tooltip
								prop="receiveCompany"
								width="80"
						></el-table-column>
						<el-table-column
								label="商品单价"
								align="center" show-overflow-tooltip
								prop="price"
								width="80"
						></el-table-column>
						<el-table-column
								label="差异数量"
								align="center" show-overflow-tooltip
								prop="differenceQty"
								width="80"
						></el-table-column>
						<el-table-column
								label="是否核销"
								align="center" show-overflow-tooltip
								prop="audit"
								width="80"
						></el-table-column>
						<el-table-column
								label="异常售后未提报金额"
								align="center" show-overflow-tooltip
								width="80"
						>
							<template #default="scope">
								{{scope.row.serviceBillAmount === 0 ? '' : scope.row.serviceBillAmount}}
							</template>
						</el-table-column>
						<el-table-column
								label="编号编码"
								align="center" show-overflow-tooltip
								prop="ruleCode"
								width="80"
						></el-table-column>
						<el-table-column
								label="订单核销细类名称"
								align="center" show-overflow-tooltip
								prop="auditDetailName"
								width="80"
						/>
						<el-table-column
								label="创建时间"
								align="center" show-overflow-tooltip
								prop="createTime"
								width="140"
						/>
<!--            <el-table-column label="操作" fixed="right" width="100" >-->
<!--              <template #default="scope">-->
<!--                <el-popconfirm v-if="scope.row.reconciliationAmount !== 0" title="是否确认?" @confirm="antiAuditHandle(scope.row.id)">-->
<!--                  <template  #reference>-->
<!--                    <el-button v-hasPerm="['sys:fileAudit:reCheck']" type="primary">反审核</el-button>-->
<!--                  </template>-->
<!--                </el-popconfirm>-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>


  </div>
</template>
